#include "wpmsghandler.h"

#include <stdlib.h> // for abort()

WPMsgHandler * WPMsgHandler::instance = 0;

WPMsgHandler::WPMsgHandler(QString filename)
    : outputFile(filename)
{
    if(instance) { qFatal("WPMsgHandler already exists"); }
    instance = this;
    
    outputFile.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text);
}

WPMsgHandler::~WPMsgHandler()
{
    outputFile.close();
}

void WPMsgHandler::handler(QtMsgType type, const char *msg)
{
    instance->doHandler(type, msg);
}

void WPMsgHandler::doHandler(QtMsgType type, const char *msg)
{
    if(hiddenMessageTypes.find(type) == hiddenMessageTypes.end()) {
        outputFile.write(msg);
        outputFile.write("\n");
        outputFile.flush();
    }
    if(type == QtFatalMsg) { abort(); }
}

void WPMsgHandler::hideMsgType(QtMsgType type, bool hide)
{
    if(hide) {
        hiddenMessageTypes.insert(type);
    } else {
        hiddenMessageTypes.remove(type);
    }
}
